package com.gdkm.servlet;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.sql.SQLException;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.beanutils.BeanUtils;

import com.gdkm.dao.UserDao;
import com.gdkm.daomain.User;
import com.gdkm.util.ActiveCodeUtils;

public class UserServlet extends HttpServlet {

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/html;charset=utf8");
		request.setCharacterEncoding("utf8");
		UserDao userDao = new UserDao();
		String op = request.getParameter("op");
		HttpSession session = request.getSession();
		// 注册普通用户
		if (op != null && op.equals("register")) {
			User user = new User();
			try {
				BeanUtils.populate(user, request.getParameterMap());// 使用beanUtils组件将注册表单的数据保存到user对象中
				user.setActiveCode(ActiveCodeUtils.createActiveCode());// 产生激活码
				user.setState(0);
				user.setRole("普通用户");
				int rows = userDao.addUser(user);
				if (rows != 0) {
					String activeUrl = request.getScheme() + "://" + request.getServerName() + ":"
							+ request.getServerPort() + request.getContextPath()
							+ "/manager/UserServlet?op=activeUser&activeCode=" + user.getActiveCode();// 激活码地址
					String emailMsg = "<a href='" + activeUrl + "'>感谢您的注册，请在24小时内点击链接完成激活</a>";// 通过超链接来激活
					request.setAttribute("msg", emailMsg);
					request.getRequestDispatcher("/manager/registerUser.jsp").forward(request, response);
				}
			} catch (Exception e) {
				e.printStackTrace();
				request.setAttribute("msg", "注册失败");
				request.getRequestDispatcher("/manager/registerUser.jsp").forward(request, response);

			}
		}
		// 激活用户
		else if (op != null && op.equals("activeUser")) {
			String activeCode = request.getParameter("activeCode");
			try {
				User user = userDao.findUserByActiveCode(activeCode);// 根据激活码查找用户
				if (user == null) {
					request.setAttribute("msg", "没有找到激活用户");
					request.getRequestDispatcher("/manager/registerUser.jsp").forward(request, response);
					return;
				}

				Date registTime = user.getRegistTime();
				System.out.println("============" + user);
				long time = System.currentTimeMillis() - registTime.getTime();// 获取激活码生成时间，单位为毫秒
				if (time / 1000 / 60 / 60 > 24) {
					request.setAttribute("msg", "激活码已超过24h有效期");
					request.getRequestDispatcher("/manager/registerUser.jsp").forward(request, response);
					return;
				}
				userDao.activeUser(activeCode);// 激活用户成功后修改用户登录状态为激活
				request.setAttribute("msg", user.getUsername() + "激活成功");
				request.getRequestDispatcher("/manager/registerUser.jsp").forward(request, response);
			} catch (SQLException e) {
				e.printStackTrace();
				request.setAttribute("msg", "激活失败");
				request.getRequestDispatcher("/manager/registerUser.jsp").forward(request, response);
			}
		}
		// 查询所有用户
		else if (op != null && op.equals("listUser")) {
			try {
				List<User> listUser = userDao.findAllUser();
				request.setAttribute("listUser", listUser);
				request.getRequestDispatcher("/manager/listUser.jsp").forward(request, response);
			} catch (SQLException e) {
				e.printStackTrace();
				response.getWriter().write("系统异常：" + e.getMessage());
			}
		}
		// 按照id删除用户
		else if (op != null && op.equals("deleteUser")) {
			int id = Integer.parseInt(request.getParameter("id"));
			try {
				userDao.deleteUser(id);
				request.getRequestDispatcher("/manager/UserServlet?op=listUser").forward(request, response);
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		// 按照id来修改密码
		else if (op != null && op.equals("updatePassword")) {
			try {
				User user = (User) session.getAttribute("user");
				String oldpwd = request.getParameter("oldpwd");
				String password = request.getParameter("newpwd");
				System.out.println(password+oldpwd);
				System.out.println();
				if (oldpwd.equals(user.getPassword())) {
					user.setPassword(password);
					userDao.updatePassword(user);
					request.setAttribute("msg", "修改密码成功");
				} else {
					request.setAttribute("msg", "输入旧密码错误");
				}
				request.getRequestDispatcher("/manager/updatePassword.jsp").forward(request, response);
			} catch (SQLException e) {
				e.printStackTrace();
			}

		}

	}

}
